/**
 * @file
 * WinRT threads to pthreads wrapper, this is cpp part
 */

extern "C"
{
	#include "wRTpthreadsTypeDef.h" 
}
#ifdef inline
#undef inline
#include <thread> 
#endif

using namespace std;
typedef struct wrtcontext {
	std::thread * workthread;
} wrtcontext;



unsigned __stdcall  win32thread_worker(void *arg)
{
	pthread_t *h = (pthread_t*)arg;
	h->ret = h->func(h->arg);
	return 0;
}

void stdfunction(void *arg)
{
	win32thread_worker(arg);
}

int pthread_create(pthread_t *thread, const void *unused_attr,
	void *(*start_routine)(void*), void *arg)
{
	thread->func = start_routine;
	thread->arg = arg;
	thread->wrtcontext= (wrtcontext*)malloc(sizeof(wrtcontext));
	thread->wrtcontext->workthread = new std::thread(stdfunction,thread);
	return !thread->wrtcontext->workthread->joinable();
}

void pthread_join(pthread_t thread, void **value_ptr)
{
	wrtcontext* context = thread.wrtcontext;
	context->workthread->join();
	if (value_ptr)
		*value_ptr = thread.ret;
	delete context->workthread;
	free(thread.wrtcontext);
}